package com.cuit.qx.service.impl;

import com.cuit.qx.bean.AddWeatherStation;
import com.cuit.qx.bean.InterfaceConfig;
import com.cuit.qx.bean.WeatherStation;
import com.cuit.qx.service.*;
import com.cuit.qx.utils.HttpUtil;
import com.cuit.qx.utils.WebSocket;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class StationInfoServiceImpl implements StationInfoService {

    private static final Logger LOG = LoggerFactory.getLogger(StationInfoServiceImpl.class);

    @Autowired
    WeatherStationService stationService;

    @Autowired
    AddWeatherStationService addStationService;

    @Autowired
    InterfaceConfigService interfaceConfigService;

    @Autowired
    ThresholdAndStationCheckService thresholdAndStationCheckService;

//    @Value("${httpUrlStation}")
    private String httpUrlStation;

    @Override
    public void execute() {
        InterfaceConfig interfaceConfigDatas = interfaceConfigService.getInterfaceConfigDatas();
        Map<String, String> params = new HashMap<>(16);
        params.put("account", interfaceConfigDatas.getAccount());
        params.put("password", interfaceConfigDatas.getPassword());
        ExecutorService executorService= Executors.newFixedThreadPool(1);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                executeTaskDescribe(params);
            }
        });
    }

    @Override
    public void liveToHistory() {

    }

    public void executeTaskDescribe(Map<String, String> params) {
        long startTime = System.currentTimeMillis();
        try {
            HttpUtil util = new HttpUtil();
            String data = util.doPost(httpUrlStation, params);
            if (data.contains("<br />")) {
                return;
            }
            JSONObject getJson = new JSONObject(data);
            String code = getJson.get("code").toString();
            String dataTo = getJson.get("data").toString();
            JSONObject getJsonTo = new JSONObject(dataTo);
//            LOG.info("获取的数据：" + getJsonTo);
            JSONArray stationDatas = getJsonTo.getJSONArray("list");
            LOG.info("Weather data number is:" + stationDatas.length());
            // 查询数据库中所有的站点信息
            List<WeatherStation> weatherStations = stationService.list();

            // 设置日期转换
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将日期转换成str
            String createTime = sdf.format(new Date());

            ArrayList<WeatherStation> weatherStationUpdateData = new ArrayList<>();
            ArrayList<WeatherStation> weatherStationCreate = new ArrayList<>();
            ArrayList<WeatherStation> weatherStationUpdate = new ArrayList<>();
            ArrayList<AddWeatherStation> addWeatherStationCreate = new ArrayList<>();

            if ("200".equals(code)) {

                for (int i = 0; i < stationDatas.length(); i++) {
                    JSONObject stationData = stationDatas.getJSONObject(i);
                    //解析气象数据入库
                    // 获取站号
                    String stationNumber = stationData.get("number").toString();
                    // 获取站名
                    String stationName = stationData.get("name").toString();
                    // 获取区县
                    String stationCounty = stationData.get("county").toString();
                    // 获取经度
                    double longitude = Double.parseDouble(stationData.get("longitude").toString());
                    // 获取纬度
                    double latitude = Double.parseDouble(stationData.get("latitude").toString());
                    // 获取站点地址
                    String stationAddress = stationData.get("address").toString();

                    boolean flag=true;
                    String id=null;
                    for (WeatherStation weatherStation : weatherStations) {
                        if(weatherStation.getStationNumber().equals(stationNumber)){
                            flag=false;
                            id=weatherStation.getSitesId();
                            break;
                        }
                    }
//                    // 判断气象数据的某一条数据是否在数据库中存在
//                    LambdaQueryWrapper<WeatherStation> query = new LambdaQueryWrapper<>();
//                    query.eq(WeatherStation::getStationNumber, stationNumber);
//                    WeatherStation one = stationService.getOne(query);
                    // 不存在-->数据库新增,state=1,存在-->数据库更新
                    if (flag) {
                        WeatherStation weather = new WeatherStation();
                        weather.setStationName(stationName);
                        weather.setStationNumber(stationNumber);
                        // 1 气象站
                        weather.setStationType("1");
                        weather.setStationAddress(stationAddress);
                        weather.setLatitude(latitude);
                        weather.setLongitude(longitude);
                        weather.setStationCounty(stationCounty);
                        weather.setState("1");
                        weather.setCreateTime(createTime);
                        weatherStationCreate.add(weather);

                        // 新增站点也存到另一个表中
                        AddWeatherStation addWeather = new AddWeatherStation();
                        addWeather.setStationName(stationName);
                        addWeather.setStationNumber(stationNumber);
                        addWeather.setStationType("1");
                        addWeather.setStationAddress(stationAddress);
                        addWeather.setLatitude(latitude);
                        addWeather.setLongitude(longitude);
                        addWeather.setStationCounty(stationCounty);
                        addWeather.setCreateTime(createTime);
                        addWeather.setIsSure("0");
                        addWeatherStationCreate.add(addWeather);
                    } else {
                        WeatherStation weather = new WeatherStation();
                        weather.setSitesId(id);
                        weather.setStationType("1");
                        weather.setStationAddress(stationAddress);
                        weather.setLatitude(latitude);
                        weather.setLongitude(longitude);
                        weather.setStationCounty(stationCounty);
                        weather.setState("1");
                        weather.setCreateTime(createTime);
                        weatherStationUpdate.add(weather);
                    }
                }
                if (weatherStationCreate.size() > 0) {
                    stationService.saveBatch(weatherStationCreate);
                    addStationService.saveBatch(addWeatherStationCreate);
                    WebSocket webSocket = new WebSocket();
                    webSocket.sendAllMessage(null);
                }
                if (weatherStationUpdate.size() > 0) {
                    stationService.updateWeatherList(weatherStationUpdate);
                }
                for (WeatherStation weatherStation : weatherStations) {
                    boolean flag = true;
                    for (int i = 0; i < stationDatas.length(); i++) {
                        JSONObject station = stationDatas.getJSONObject(i);
                        if (weatherStation.getStationNumber().equals(station.get("number").toString())) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        weatherStation.setState("0");
                        weatherStation.setCreateTime(createTime);
                        weatherStationUpdateData.add(weatherStation);
                    }
                }
                if (weatherStationUpdateData.size() > 0) {
                    stationService.updateWeatherList(weatherStationUpdateData);
                }
            }else {
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("Station ruku job task is error info：" + e);
        }

        long endTime = System.currentTimeMillis();
        LOG.info("Deal with station ruku use" + (endTime - startTime) + "=========");

        thresholdAndStationCheckService.checkThreshold();
    }

}
